# -*- coding:utf-8 -*-
# Created by Jin(jinzhencheng@outlook.com) at 2018/8/3 13:51


from bd_spider.util import db_helper
from bd_spider.util import logger
from bd_spider.config import RedisConfig
from bd_spider.entity import  BaiJiaHao
from datetime import datetime
from sqlalchemy.sql import exists

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

__the_logger = logger.get_logger()
__redis_helper = db_helper.RedisHelper()
__mysql_helper = db_helper.MySQLHelper("bd_article_sys")
__filter_key = RedisConfig.BAIJIAHAO_FILTER


def filter(item):
    is_exists = __redis_helper.is_exists_in_set(__filter_key, item["app_id"])
    if not is_exists:
        __redis_helper.push_to_set(__filter_key, item["app_id"])
        item["is_exists"] = "no"
        __the_logger.info("Push an 'app_id' into baijiahao:filter in redis.")

def inject(item):
    entity = BaiJiaHao()
    entity.id = 0
    entity.is_valid = item["is_valid"]
    entity.app_id = item["app_id"]
    entity.add_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    entity.category = item["category"]
    entity.home_url = item["home_url"]
    entity.add_time = item["add_time"]
    update_dict = dict()
    update_dict[BaiJiaHao.update_time] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    if "name" in item:
        entity.name = item["name"]
        update_dict[BaiJiaHao.name] = item["name"]
    if "description" in item:
        entity.description = item["description"]
        update_dict[BaiJiaHao.description] = item["description"]
    if "remark" in item:
        entity.remark = item["remark"]
        update_dict[BaiJiaHao.remark] = item["remark"]
    if "fans" in item:
        fans = item["fans"]
        if u"万" in fans and u"粉丝" in fans:
            fans = fans.split(' ')[1]
            fans = float(fans[:len(fans) - 1]) * 10000
        elif u"万" in fans:
            fans = float(fans[:len(fans) - 1]) * 10000
        entity.fans = fans
        update_dict[BaiJiaHao.fans] = fans
    if "follow" in item:
        follow = item["follow"]
        if u"关注" in follow and u"关注" != follow:
            follow = follow.split(" ")[1]
            follow = float(follow[:len(follow) - 1]) * 10000
        entity.follow = follow
        update_dict[BaiJiaHao.follow] = follow
    session = None
    try:
        __mysql_helper.open_driver()
        session = __mysql_helper.session
        is_in = session.query(exists().where(BaiJiaHao.app_id == item["app_id"])).scalar()
        if is_in:
            session.query(BaiJiaHao).filter(BaiJiaHao.app_id == item["app_id"]) \
                .update(update_dict)
            __the_logger.info("Update ---- BaiJiaHao:app_id(%s) into bd_article_sys.baijiahao table" % item["app_id"])
        else:
            session.add(entity)
            __the_logger.info("Add ---- BaiJiaHao:app_id(%s) into bd_article_sys.baijiahao table" % item["app_id"])
        session.commit()
    except Exception, e:
        if session:
            session.rollback()
        __the_logger.error("Insert BaiJiaHao:app_id(%s) into bd_article_sys.baijiahao table error, detail: %s" % (item["app_id"], e.message))

def list(is_valid=1):
    try:
        __mysql_helper.open_driver()
        session = __mysql_helper.session
        result = session.query(BaiJiaHao.id, BaiJiaHao.app_id)\
            .filter(BaiJiaHao.is_valid == is_valid)\
            .all()
        return result
    except Exception, e:
        __the_logger.error("List BaiJiaHao from bd_article_sys.baijiahao table error, detail: %s" % e.message)

